﻿
/*
Javascript Syntax rule for SupertreeTextEditor

Author: Feng Weiguo ( 冯卫国 )
Mail: forxm@21cn.com
Web: www.supertree.org
2008-1
update 2008-9

All Rights Reserved, 2008-9

LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.
*/

$ec.$preload(
	"org.supertree.editor.RuleJavascript",
	function()
	{
		var RC= $ec.$import("org.supertree.editor.RuleCompiler").prototype;
		
		this.prototype=
		{
//////////////////////////////
// EC-CLASS BODY
//////////////////////////////
			RuleJavascript: function()
			{
				throw "can not instantiate RuleJavascript";
			},
			
			sName: "Javascript",
			
			sEndStack: "|0|0,15|0,13|0,12|0,11|0,10|0,4,s),4|",
			
			aInsert:[
				"if...else","\nif\n{\n}\nelse\n{\n}",
				"do...while","\do\n{\n}\while();",
				"switch","\nswitch()\n{\n    case \"\":\n        break;\n    default:\n        break;\n}"
				]
			
//////////////////////////////
// END EC-CLASS BODY	//NOTE - DO NOT CHANGE THESE 3 LINES, the ide wizards may use them.
//////////////////////////////
		}
		
		//construct rule
		
		//auxiliary rule item
		var _rule= this.prototype._rule=
		{
			//from MS Jscript
			sJsFunction: "GetObject|ScriptEngine|ScriptEngineBuildVersion|ScriptEngineMajorVersion|ScriptEngineMinorVersion",
			sJsMethod: "apply|call|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|hasOwnProperty|isPrototypeOf|localeCompare|pop|push|random|shift|splice|toDateString|toExponential|toFixed|toLocaleDateString|toLocaleLowercase|toLocaleTimeString|toLocaleUppercase|toPrecision|toTimeString|unshift"+"|abs|acos|anchor|asin|atan|atan2|atEnd|big|blink|bold|ceil|charAt|charCodeAt|compile|concat|cos|dimensions|escape|eval|exec|exp|fixed|floor|fontcolor|fontsize|fromCharCode|getDate|getDay|getFullYear|getHours|getItem|getMilliseconds|getMinutes|getMonth|getSeconds|getTime|getTimezoneOffset|getUTCDate|getUTCDay|getUTCFullYear|getUTCHours|getUTCMilliseconds|getUTCMinutes|getUTCMonth|getUTCSeconds|getVarDate|getYear|indexOf|isFinite|isNaN|italics|item|join|lastIndexOf|lbound|link|log|match|max|min|moveFirst|moveNext|parse|parseFloat|parseInt|pow|random|replace|reverse|round|search|setDate|setFullYear|setHours|setMilliseconds|setMinutes|setMonth|setSeconds|setTime|setUTCDate|setUTCFullYear|setUTCHours|setUTCMilliseconds|setUTCMinutes|setUTCMonth|setUTCSeconds|setYear|sin|slice|small|sort|split|sqrt|strike|sub|substr|substring|sup|tan|test|toArray|toGMTString|toLocaleString|toLowerCase|toString|toUpperCase|toUTCString|ubound|unescape|UTC|valueOf",
			sJsObject: "ActiveXObject|Array|Boolean|Date|Dictionary|Enumerator|Error|FileSystemObject|Function|Global|Math|Number|Object|RegExp|String|VBArray",
			sJsOperator: "delete|instanceof|new|typeof|void",
			sJsProperty: "callee|global|ignoreCase|lastMatch|lastParen|leftContext|message|multiline|name|propertyIsEnumeramble|rightContext|undefined"+"|arguments|caller|constructor|description|E|index|Infinity|input|lastIndex|length|LN2|LN10|LOG2E|LOG10E|MAX_VALUE|MIN_VALUE|NaN|NEGATIVE_INFINITY|number|PI|POSITIVE_INFINITY|prototype|source|SQRT1_2|SQRT2",
			sJsStatement: "break|catch|@cc_on|continue|do|while|for|for|in|function|@if|if|else|return|@set|switch|case|default|this|throw|try|var|while|with|finally",

			sJsScriptingMethod: "Add|BuildPath|Close|Copy|CopyFile|CopyFolder|CreateFolder|CreateTextFile|Delete|DeleteFile|DeleteFolder|DriveExists|Exists|FileExists|FolderExists|GetAbsolutePathName|GetBaseName|GetDrive|GetDriveName|GetExtensionName|GetFile|GetFileName|GetFileVersion|GetFolder|GetParentFolderName|GetSpecialFolder|GetTempName|Items|Keys|Move|MoveFile|MoveFolder|OpenAsTextStream|OpenTextFile|Read|ReadAll|ReadLine|Remove|RemoveAll|Skip|SkipLine|Write|WriteBlankLines|WriteLine",
			sJsScriptingProperty: "AtEndOfLine|AtEndOfStream|Attributes|AvailableSpace|Column|CompareMode|Count|DateCreated|DateLastAccessed|DateLastModified|Drive|DriveLetter|Drives|DriveType|Files|FileSystem|FreeSpace|IsReady|IsRootFolder|Item|Key|Line|Name|ParentFolder|Path|RootFolder|SerialNumber|ShareName|ShortName|ShortPath|Size|SubFolders|TotalSize|Type|VolumeName",

			//from MS DHTML
			sDhtmlProperty: "abbr|accelerator|accept|acceptCharset|accessKey|action|activeElement|additive|align|aLink|alinkColor|allowTransparency|alt|altHTML|altKey|altLeft|appCodeName|APPLICATION|appMinorVersion|appName|appVersion|archive|ATOMICSELECTION|autocomplete|availHeight|availWidth|axis|background|backgroundAttachment|backgroundColor|backgroundImage|backgroundPosition|backgroundPositionX|backgroundPositionY|backgroundRepeat|balance|Banner|BannerAbstract|BaseHref|behavior|bgColor|bgProperties|blockDirection|border|borderBottom|borderBottomColor|borderBottomStyle|borderBottomWidth|borderCollapse|borderColor|borderColorDark|borderColorLight|borderLeft|borderLeftColor|borderLeftStyle|borderLeftWidth|borderRight|borderRightColor|borderRightStyle|borderRightWidth|borderStyle|borderTop|borderTopColor|borderTopStyle|borderTopWidth|borderWidth|bottom|bottomMargin|boundingHeight|boundingLeft|boundingTop|boundingWidth|browserLanguage|bufferDepth|button|cancelBubble|canHaveChildren|canHaveHTML|caption|cellIndex|cellPadding|cellSpacing|ch|charset|checked|chOff|cite|classid|className|clear|clientHeight|clientLeft|clientTop|clientWidth|clientX|clientY|clip|clipBottom|clipLeft|clipRight|clipTop|closed|code|codeBase|codeType|color|colorDepth|cols|colSpan|compact|compatMode|complete|content|contentEditable|contentOverflow|contentWindow|cookie|cookieEnabled|coords|Count|cpuClass|cssText|ctrlKey|ctrlLeft|cursor|data|dataFld|dataFormatAs|dataPageSize|dataSrc|dateTime|declare|defaultCharset|defaultChecked|defaultSelected|defaultStatus|defaultValue|defer|designMode|deviceXDPI|deviceYDPI|dialogArguments|dialogHeight|dialogLeft|dialogTop|dialogWidth|dir|direction|disabled|display|doctype|document|documentElement|domain|dropEffect|dynsrc|effectAllowed|encoding|enctype|event|expando|face|fgColor|FieldDelim|fileCreatedDate|fileModifiedDate|fileSize|fileUpdatedDate|filter|firstChild|font|fontFamily|fontSize|fontSmoothingEnabled|fontStyle|fontVariant|fontWeight|form|frame|frameBorder|frameElement|frameSpacing|fromElement|galleryImg|hash|hasLayout|headers|height|hidden|hideFocus|host|hostname|href|hreflang|hspace|htmlFor|htmlText|httpEquiv|id|imeMode|implementation|indeterminate|index|innerHTML|innerText|isContentEditable|isDisabled|isMap|isMultiLine|isOpen|isTextEdit|keyCode|label|lang|language|lastChild|lastModified|layoutFlow|layoutGrid|layoutGridChar|layoutGridLine|layoutGridMode|layoutGridType|left|leftMargin|length|letterSpacing|lineBreak|lineHeight|link|linkColor|listStyle|listStyleImage|listStylePosition|listStyleType|logicalXDPI|logicalYDPI|longDesc|loop|lowsrc|margin|marginBottom|marginHeight|marginLeft|marginRight|marginTop|marginWidth|maxLength|media|menuArguments|method|Methods|minHeight|MoreInfo|multiple|name|nameProp|nextPage|nextSibling|nodeName|nodeType|nodeValue|noHref|noResize|noShade|noWrap|object|offscreenBuffering|offsetHeight|offsetLeft|offsetParent|offsetTop|offsetWidth|offsetX|offsetY|onLine|opener|outerHTML|outerText|overflow|overflowX|overflowY|ownerDocument|owningElement|padding|paddingBottom|paddingLeft|paddingRight|paddingTop|pageBreakAfter|pageBreakBefore|palette|parent|parentElement|parentNode|parentStyleSheet|parentTextEdit|parentWindow|pathname|pixelBottom|pixelHeight|pixelLeft|pixelRight|pixelTop|pixelWidth|platform|pluginspage|port|posBottom|posHeight|position|posLeft|posRight|posTop|posWidth|previousSibling|profile|propertyName|protocol|pseudoClass|qualifier|readOnly|readyState|reason|recordNumber|recordset|referrer|rel|repeat|returnValue|rev|right|rightMargin|rowIndex|rows|rowSpan|rubyAlign|rubyOverhang|rubyPosition|rules|saveType|scheme|scope|scopeName|screenLeft|screenTop|screenX|screenY|scroll|scrollAmount|scrollbar3dLightColor|scrollbarArrowColor|scrollbarBaseColor|scrollbarDarkShadowColor|scrollbarFaceColor|scrollbarHighlightColor|scrollbarShadowColor|scrollbarTrackColor|scrollDelay|scrollHeight|scrolling|scrollLeft|scrollTop|scrollWidth|search|sectionRowIndex|SECURITY|selected|selectedIndex|selector|selectorText|self|shape|shiftKey|shiftLeft|size|sourceIndex|span|specified|src|srcElement|srcFilter|srcUrn|standby|start|status|STYLE|styleFloat|summary|systemLanguage|tabIndex|tableLayout|tabStop|tagName|tagUrn|target|text|textAlign|textAlignLast|textAutospace|textDecoration|textDecorationBlink|textDecorationLineThrough|textDecorationNone|textDecorationOverline|textDecorationUnderline|textIndent|textJustify|textKashidaSpace|textOverflow|textTransform|textUnderlinePosition|tFoot|tHead|title|toElement|top|topMargin|trueSpeed|type|typeDetail|unicodeBidi|uniqueID|units|UNSELECTABLE|updateInterval|URL|URLUnencoded|urn|useMap|userAgent|userLanguage|vAlign|value|valueType|vcard_name|version|verticalAlign|viewInheritStyle|viewLink|viewMasterTab|visibility|vLink|vlinkColor|volume|vspace|wheelDelta|whiteSpace|width|wordBreak|wordSpacing|wordWrap|wrap|writingMode|x|XMLDocument|XMLNS|XSLDocument|y|zIndex|zoom",
			sDhtmlMethod: "add|addBehavior|AddChannel|AddDesktopComponent|AddFavorite|addImport|addPageRule|addReadRequest|addRule|alert|appendChild|appendData|applyElement|assign|attachEvent|AutoCompleteSaveForm|AutoScan|back|blur|ChooseColorDlg|clear|clearAttributes|clearData|clearInterval|clearRequest|clearTimeout|click|cloneNode|close|collapse|compareEndPoints|componentFromPoint|confirm|contains|createAttribute|createCaption|createComment|createControlRange|createDocumentFragment|createElement|createEventObject|createPopup|createRange|createRangeCollection|createStyleSheet|createTextNode|createTextRange|createTFoot|createTHead|deleteCaption|deleteCell|deleteData|deleteRow|deleteTFoot|deleteTHead|detachEvent|doImport|doReadRequest|doScroll|dragDrop|duplicate|elementFromPoint|empty|execCommand|execScript|expand|findText|fireEvent|firstPage|focus|forward|getAdjacentText|getAttribute|getAttributeNode|getBookmark|getBoundingClientRect|getClientRects|getData|getElementById|getElementsByName|getElementsByTagName|getExpression|getNamedItem|go|hasChildNodes|hasFeature|hasFocus|hide|ImportExportFavorites|inRange|insertAdjacentElement|insertAdjacentHTML|insertAdjacentText|insertBefore|insertCell|insertData|insertRow|isEqual|IsSubscribed|item|javaEnabled|lastPage|mergeAttributes|move|moveBy|moveEnd|moveRow|moveStart|moveTo|moveToBookmark|moveToElementText|moveToPoint|namedItem|namedRecordset|navigate|NavigateAndFind|nextPage|normalize|open|parentElement|pasteHTML|previousPage|print|prompt|queryCommandEnabled|queryCommandIndeterm|queryCommandState|queryCommandSupported|queryCommandValue|recalc|refresh|releaseCapture|reload|remove|removeAttribute|removeAttributeNode|removeBehavior|removeChild|removeExpression|removeNamedItem|removeNode|removeRule|replace|replaceAdjacentText|replaceChild|replaceData|replaceNode|reset|resizeBy|resizeTo|scroll|scrollBy|scrollIntoView|scrollTo|select|setActive|setAttribute|setAttributeNode|setCapture|setData|setEndPoint|setExpression|setInterval|setNamedItem|setTimeout|show|ShowBrowserUI|showHelp|showModalDialog|showModelessDialog|splitText|start|stop|submit|substringData|swapNode|tags|taintEnabled|urns|write|writeln",
			sDhtmlEvent: "onabort|onactivate|onafterprint|onafterupdate|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditfocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror|onerrorupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmouseout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizeend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload",
			sDhtmlSet: "all|anchors|applets|areas|attributes|behaviorUrns|blockFormats|bookmarks|boundElements|cells|childNodes|children|controlRange|elements|embeds|filters|fonts|forms|frames|images|imports|links|mimeTypes|namespaces|options|pages|plugins|rows|rules|scripts|styleSheets|tBodies|TextRange|TextRectangle",
			sDhtmlObject: "window",
			
			sEcKey: "\\$import|\\$eid|\\$bind|\$notify|\\$derive|\\$preload|\\$find|\\$init|\\$apply|\\$res|\\$\\$|\\$(?=\\()",
			
			ruleJsTokenEnd: 
				[
					"([\\)\\}\\]])|([^\\)\\}\\]])|($)",
					["err","err",-1],	// unmatch ')' or '}' or ']'
					["void","",1,"","this.rule"],	// char except ')' or '}' or ']'
					["","",0],	// next line
					["","",-1]	//match enclosed token
				],
			
			ruleJsTokenEnd2: 		// for ')', check next divide('/')
				[
					"([\\)\\}\\]])|([^\\)\\}\\]])|($)",
					["err","err",-1],	// unmatch ')' or '}' or ']'
					["void","",1,"","this.rule"],	// char except ')' or '}' or ']'
					["","",0],	// next line
					["","",1,"","this._rule.ruleJsWordEnd2"]	//match enclosed token
				],
				
			ruleJsInnerComment:
				[
					"(\\*\\/)|($)",
					["Green","Green",-1],	// */
					["","Green",0]		// next line
				],
			
			ruleJsEndComment:
				[
					"($)",
					["","Green",-1]	// to line end
				],
			
			ruleJsWordEnd:	//for divide(/) checking
				[
					"(\\/\\*)|(\\/\\/.*)|(\\/)|([\\s\\u00A0]+)|(.)|($)",
					["Green","",1,"","this._rule.ruleJsInnerComment"],	// /*
					["Green","",0,"","this._rule.ruleJsEndComment"],	// //
					["","",-1],		// / divide, not regexp start
					["","",0],	//skip space
					["void","",-1],	//pop back
					["","",0]	// next line
				],
			ruleJsWordEnd2:		//ruleJsWordEnd for ')'
				[
					"(\\/\\*)|(\\/\\/.*)|(\\/)|([\\s\\u00A0]+)|(.)|($)",
					["Green","",1,"","this._rule.ruleJsInnerComment"],	// /*
					["Green","",0,"","this._rule.ruleJsEndComment"],	// //
					["","",-2],		// / divide, not regexp start
					["","",0],	//skip space
					["void","",-2],	//pop back
					["","",0]	// next line
				]
		};
		
		this.prototype.rule=
		[
			"(\\/\\*)|(\\/\\/.*)|([\\)\\}\\]])|(\\()|(\\{)|(\\[)|(\\/)|(')|(\")|(\\b(?:"+_rule.sJsOperator+"|"+_rule.sJsStatement+")\\b)|(\\b(?:"+_rule.sJsFunction+"|"+_rule.sJsObject+")\\b)|(\\b(?:"+_rule.sJsMethod+"|"+_rule.sJsProperty+"|"+_rule.sJsScriptingMethod+"|"+_rule.sJsScriptingProperty+")\\b)|(\\b(?:"+_rule.sDhtmlProperty+"|"+_rule.sDhtmlMethod+"|"+_rule.sDhtmlEvent+"|"+_rule.sDhtmlSet+"|"+_rule.sDhtmlObject+")\\b)|(\\$ec\\b)|(\\b\\w+\\b)|($)",
			["Green","",1,"",_rule.ruleJsInnerComment],	// /*
			["Green","",0,"",_rule.ruleJsEndComment],	// //
			["void","",-1],	// ')', '}' or ']', pop back
			["","",1,")",_rule.ruleJsTokenEnd2],	// '('
			["","",1,"}",_rule.ruleJsTokenEnd],	// '{'
			["","",1,"]",_rule.ruleJsTokenEnd],	// '['
			["Fuchsia","",1,"",		// / regexp
				[
					"(\\\\.)|(\\/[ig]*)|($)",
					["Fuchsia","Fuchsia",0],		// \. continue
					["Fuchsia","Fuchsia",-1],		// / end
					["err","err",-1]	// error, not enclosed in same line
				]
			],
			["Fuchsia","",1,"",	// '
				[
					//"(\\\\')|(')|($)",
					"(\\\\.)|(')|($)",
					["Fuchsia","Fuchsia",0],		// \' or any \. continue
					["Fuchsia","Fuchsia",-1],	// ' end
					["err","err", -1]	// error, not enclosed in same line
				]
			],
			["Fuchsia","",1,"",	// "
				[
					//"(\\\\\")|(\")|($)",
					"(\\\\.)|(\")|($)",
					["Fuchsia","Fuchsia",0],		// \" or any \. continue
					["Fuchsia","Fuchsia",-1],	// " end
					["err","err", -1]	// error, not enclosed in same line
				]
			],
			["BlueB","",1,"",_rule.ruleJsWordEnd],		// main key
			["BrownB","",1,"",_rule.ruleJsWordEnd],		// global object and function
			["Blue","",1,"",_rule.ruleJsWordEnd],		// method and property
			["Brown","",1,"",_rule.ruleJsWordEnd],		// dhtml
			["BlueB","",1,"",		//ec key
				[
					"(\\.)|([^\\.])|($)",
					["","",1,"",		// .
						[
							"("+_rule.sEcKey+")|(.)|($)",
							["BlueB","",-2],
							["void","",-2],
							["","",-2]
						]
					],
					["void","",-1],
					["","",-1]
				]
			],
			["","",1,"",_rule.ruleJsWordEnd],		// any word
			["","",0]	// next line
		];
		
		RC.Compile(this.prototype);
	}
);
